package com.example.utils;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhangs
 * @version v1.0
 * @decription
 * @date 2021/4/7 22:33
 **/
public class ExchangerDemo {
    private static final Exchanger<String> EXCHANGER =
            new Exchanger<>();
    private static final ExecutorService threadPool =
            Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(() -> {
            Thread t = Thread.currentThread();
            String A = t.getName() + "的数据";
            try {
                System.out.println("当前线程：" + t.getName()
                        + " 持有的数据：" + A);
                Thread.sleep(2000);
                String exchange = EXCHANGER.exchange(A);
                System.out.println("当前线程：" + t.getName()
                        + " 获取的数据：" + exchange);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        threadPool.execute(() -> {
            Thread t = Thread.currentThread();
            String B = t.getName() + "的数据";
            try {
                System.out.println("当前线程：" + t.getName()
                        + " 持有的数据：" + B);
                String exchange = EXCHANGER.exchange(B);
                System.out.println("当前线程：" + t.getName()
                        + " 获取的数据：" + exchange);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 关闭线程池
        threadPool.shutdown();
    }
}
